<?php
/** 
 * CRON daemon
 *
 * @version 0.2a
 */

// No direct access
defined( "__DEENZO__" ) or die( "deenzo$" ); 

// Loading dependencies
coreutil( "cmdl" )       or kill( "cmdl$" );
coreutil( "datetime" )   or kill( "datetime$" );
coreutil( "filesystem" ) or kill( "filesystem$" );

// Loading SQL
sql( "cron.d.s" ) or kill( "cron.d.s$" );

function crond() {

    $crontab = sql("CRONTAB", "-l");
	
	if ( !is_array( $crontab ) ) return true;
    
    foreach ( (array) $crontab as $crond ) {
    
        $crond = (object) $crond;
        
        // Calculatin next CRON-time
        $crond->cron = timestamp( $crond->timestamp
                                , $crond->cron );
     
        /* Execute SH */  
        $sh = __CGI__ . " " . __DIR__ . "/$crond->sh";
			
	    bash( $sh );
		
		// Resaving CROND for next            
        sql( "crontab.(sh eq '$crond->sh')", "cron=$crond->cron" );
      
    } 
}

/** Register a CRON */
function crontab( $crond ) {
	
	$crond = (object) cmdl( $crond );
		
	/* Get next run date-time */
	$crond->cron = timestamp( $crond->timestamp );
		
	if ( !$crond->cron ) return false;
		
	sql("crontab", array( "sh"        => $crond->sh
                        , "timestamp" => $crond->timestamp
                        , "cron"      => $crond->cron ) );
}

function unregister_cron( $sh ) {
    return sql( "crontab.(sh='$sh')", null );
}